/**
 * SteHub 主JavaScript文件
 * 提供通用功能和工具函数
 */

class SteHub {
    constructor() {
        this.socket = null;
        this.currentUser = null;
        this.init();
    }

    init() {
        // 初始化工具提示
        this.initTooltips();
        
        // 初始化Toast通知
        this.initToasts();
        
        // 初始化Socket.IO连接（如果用户已登录）
        if (typeof currentUser !== 'undefined' && currentUser && currentUser.is_authenticated) {
            this.initSocket();
        }
        
        // 绑定全局事件
        this.bindEvents();
    }

    initTooltips() {
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
    }

    initToasts() {
        const toastElList = [].slice.call(document.querySelectorAll('.toast'));
        toastElList.map(function (toastEl) {
            return new bootstrap.Toast(toastEl).show();
        });
    }

    initSocket() {
        this.socket = io({
            transports: ['websocket', 'polling'],
            reconnection: true,
            reconnectionDelay: 1000,
            reconnectionDelayMax: 5000,
            reconnectionAttempts: Infinity
        });

        this.socket.on('connect', () => {
            console.log('Socket.IO 连接成功');
            this.showNotification('连接成功', 'success');
        });

        this.socket.on('disconnect', () => {
            console.log('Socket.IO 连接断开');
            this.showNotification('连接断开', 'warning');
        });

        this.socket.on('reconnect', () => {
            console.log('Socket.IO 重新连接');
            this.showNotification('重新连接成功', 'info');
        });

        // 监听新消息
        this.socket.on('new_message', (data) => {
            this.handleNewMessage(data);
        });

        // 监听用户状态变化
        this.socket.on('user_status_change', (data) => {
            this.handleUserStatusChange(data);
        });

        // 监听通知
        this.socket.on('notification', (data) => {
            this.handleNotification(data);
        });
    }

    bindEvents() {
        // 全局点击事件处理
        document.addEventListener('click', (e) => {
            // 处理外部链接
            if (e.target.matches('a[href^="http"]') && !e.target.href.includes(window.location.hostname)) {
                e.preventDefault();
                this.openExternalLink(e.target.href);
            }
        });

        // 表单提交处理
        document.addEventListener('submit', (e) => {
            this.handleFormSubmit(e);
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            this.handleKeyboardShortcuts(e);
        });
    }

    handleFormSubmit(e) {
        const form = e.target;
        const submitBtn = form.querySelector('button[type="submit"]');
        
        if (submitBtn) {
            // 显示加载状态
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<span class="loading-spinner me-2"></span>处理中...';
            submitBtn.disabled = true;

            // 3秒后恢复（防止永久禁用）
            setTimeout(() => {
                if (submitBtn.disabled) {
                    submitBtn.innerHTML = originalText;
                    submitBtn.disabled = false;
                }
            }, 3000);
        }
    }

    handleKeyboardShortcuts(e) {
        // Ctrl + K 聚焦搜索框
        if (e.ctrlKey && e.key === 'k') {
            e.preventDefault();
            const searchInput = document.querySelector('input[type="search"]');
            if (searchInput) {
                searchInput.focus();
            }
        }

        // ESC 关闭模态框
        if (e.key === 'Escape') {
            const openModal = document.querySelector('.modal.show');
            if (openModal) {
                const modal = bootstrap.Modal.getInstance(openModal);
                if (modal) {
                    modal.hide();
                }
            }
        }
    }

    handleNewMessage(data) {
        // 显示桌面通知
        if (this.shouldShowNotification()) {
            this.showDesktopNotification('新消息', {
                body: `${data.sender}: ${data.content.substring(0, 50)}...`,
                icon: data.sender_avatar || '/static/images/default-avatar.png'
            });
        }

        // 播放提示音
        this.playNotificationSound();

        // 更新UI
        this.updateMessageDisplay(data);
    }

    handleUserStatusChange(data) {
        // 更新用户状态显示
        const userElement = document.querySelector(`[data-user-id="${data.user_id}"]`);
        if (userElement) {
            const statusElement = userElement.querySelector('.user-status');
            if (statusElement) {
                statusElement.className = `user-status status-${data.status}`;
                statusElement.title = this.getStatusText(data.status);
            }
        }
    }

    handleNotification(data) {
        this.showNotification(data.message, data.type || 'info');
    }

    showNotification(message, type = 'info') {
        // 创建Toast元素
        const toastContainer = document.getElementById('toast-container') || this.createToastContainer();
        const toastId = 'toast-' + Date.now();
        
        const toastHtml = `
            <div id="${toastId}" class="toast align-items-center text-bg-${type} border-0" role="alert">
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
                </div>
            </div>
        `;
        
        toastContainer.insertAdjacentHTML('beforeend', toastHtml);
        
        const toastElement = document.getElementById(toastId);
        const toast = new bootstrap.Toast(toastElement);
        toast.show();
        
        // 自动移除DOM元素
        toastElement.addEventListener('hidden.bs.toast', () => {
            toastElement.remove();
        });
    }

    createToastContainer() {
        const container = document.createElement('div');
        container.id = 'toast-container';
        container.className = 'toast-container position-fixed top-0 end-0 p-3';
        container.style.zIndex = '9999';
        document.body.appendChild(container);
        return container;
    }

    showDesktopNotification(title, options) {
        if (!('Notification' in window)) {
            return;
        }

        if (Notification.permission === 'granted') {
            new Notification(title, options);
        } else if (Notification.permission !== 'denied') {
            Notification.requestPermission().then(permission => {
                if (permission === 'granted') {
                    new Notification(title, options);
                }
            });
        }
    }

    playNotificationSound() {
        const audio = new Audio('/static/sounds/notification.mp3');
        audio.volume = 0.3;
        audio.play().catch(() => {
            // 忽略播放错误
        });
    }

    shouldShowNotification() {
        // 检查页面是否可见
        if (document.hidden) {
            return true;
        }
        
        // 检查是否在聊天页面
        const isChatPage = window.location.pathname.includes('/chat');
        return !isChatPage;
    }

    getStatusText(status) {
        const statusMap = {
            'online': '在线',
            'offline': '离线',
            'away': '离开',
            'busy': '忙碌'
        };
        return statusMap[status] || '未知';
    }

    updateMessageDisplay(data) {
        // 在聊天界面更新消息显示
        const chatMessages = document.querySelector('.chat-messages');
        if (chatMessages) {
            const messageElement = this.createMessageElement(data);
            chatMessages.appendChild(messageElement);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
    }

    createMessageElement(data) {
        const isOwn = data.sender_id === currentUser.id;
        const messageClass = isOwn ? 'own' : 'other';
        
        return `
            <div class="chat-message ${messageClass} fade-in">
                <div class="d-flex align-items-start">
                    <img src="${data.sender_avatar || '/static/images/default-avatar.png'}" 
                         class="avatar me-2" 
                         alt="${data.sender}">
                    <div class="flex-grow-1">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <small class="fw-bold">${data.sender}</small>
                            <small class="text-muted">${this.formatTime(data.timestamp)}</small>
                        </div>
                        <div class="message-content">${this.escapeHtml(data.content)}</div>
                    </div>
                </div>
            </div>
        `;
    }

    formatTime(timestamp) {
        const date = new Date(timestamp);
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60000) { // 1分钟内
            return '刚刚';
        } else if (diff < 3600000) { // 1小时内
            return Math.floor(diff / 60000) + '分钟前';
        } else if (diff < 86400000) { // 1天内
            return Math.floor(diff / 3600000) + '小时前';
        } else {
            return date.toLocaleDateString();
        }
    }

    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    openExternalLink(url) {
        if (confirm('您将要访问外部网站：' + url + '\n\n是否继续？')) {
            window.open(url, '_blank', 'noopener,noreferrer');
        }
    }

    // API调用工具函数
    async apiCall(url, options = {}) {
        const defaultOptions = {
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            credentials: 'same-origin'
        };

        const mergedOptions = { ...defaultOptions, ...options };
        
        try {
            const response = await fetch(url, mergedOptions);
            const data = await response.json();
            
            if (!response.ok) {
                throw new Error(data.message || '请求失败');
            }
            
            return data;
        } catch (error) {
            console.error('API调用失败:', error);
            this.showNotification(error.message, 'danger');
            throw error;
        }
    }

    // 文件上传工具函数
    async uploadFile(file, onProgress = null) {
        const formData = new FormData();
        formData.append('file', file);
        
        try {
            const response = await fetch('/api/upload', {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });
            
            if (!response.ok) {
                throw new Error('文件上传失败');
            }
            
            const data = await response.json();
            return data;
        } catch (error) {
            console.error('文件上传失败:', error);
            this.showNotification('文件上传失败', 'danger');
            throw error;
        }
    }

    // 工具函数：防抖
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 工具函数：节流
    throttle(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }
}

// 全局工具函数
window.formatFileSize = function(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

window.copyToClipboard = async function(text) {
    try {
        await navigator.clipboard.writeText(text);
        return true;
    } catch (err) {
        // 降级方案
        const textArea = document.createElement('textarea');
        textArea.value = text;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        return true;
    }
};

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    window.steHub = new SteHub();
});

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = SteHub;
}